<template>
  <div class="system">
    <el-main>
      <el-tabs style="margin:20px 0;" v-model="activeName">
        <el-tab-pane label="账号设置" name="first">
          <div style="margin-bottom:20px;">
            <el-button v-if="rid == 0" type="primary" @click="CreatCancle = true">创建账号</el-button>
          </div>
          <el-table :data="userData" border style="width: 100%">
            <el-table-column prop="username" label="账号名称" align="center">
            </el-table-column>
            <el-table-column prop="role_name" align="center" label="账号类型">
            </el-table-column>
            <el-table-column prop="position" align="center" label="联系人">
            </el-table-column>
            <el-table-column prop="mobile" align="center" label="联系方式">
            </el-table-column>
            <el-table-column align="center" label="企业数量">
              <template slot-scope="scope">
                <span style="cursor: pointer;;" @click="UserListGO(scope.row)">{{ scope.row.num }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="create_on" align="center" label="创建时间">
            </el-table-column>
            <el-table-column prop="address" align="center" label="操作">
              <template slot-scope="scope">
                <el-button type="text" v-if="rid == 0" class="editText" @click="exitUser(scope.row.id)">修改</el-button>
                <el-button type="text" v-if="rid == 0" class="deletText" @click="deleteUser(scope.row.id)">删除
                </el-button>
                <el-button type="text" v-if="rid == 0" class="ck" @click="resetUser(scope.row.id)">重置密码</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="权限设置" name="second">
          <div class="fc">
            <el-table :header-cell-style="{ background: '#F3F8FE' }" :data="tableData" border
              style="width: 100%;margin: 20px 0;">
              <!-- <el-table-column
                  prop="name"
                  align="center"
                  label="项目名称"
                   >
                </el-table-column> -->
              <el-table-column prop="name" align="center" label="账号类型">
              </el-table-column>
              <el-table-column label="最大专利管理量" align="center">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: center;align-items: center;">
                    <el-input ref="myNameId" :readonly="readonly" v-model="system[0].max_patent_num"></el-input>
                    <p class="context" style="margin-left:10px;">个</p>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="竞争对手数量" align="center">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: center;align-items: center;">
                    <el-input :readonly="readonly" v-model="system[0].rivals_num"></el-input>
                    <p class="context" style="margin-left:10px;">个</p>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="费用报警数量" align="center">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: center;align-items: center;">
                    <el-input :readonly="readonly" v-model="system[0].cost_warning_num"></el-input>
                    <p class="context" style="margin-left:10px;">个</p>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="绑定用户通知数量" align="center">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: center;align-items: center;">
                    <el-input :readonly="readonly" v-model="system[0].notice_user_num"></el-input>
                    <p class="context" style="margin-left:10px;">个</p>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="业务关键词数量" align="center">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: center;align-items: center;">
                    <el-input :readonly="readonly" v-model="system[0].sales_key_num"></el-input>
                    <p class="context" style="margin-left:10px;">个</p>
                  </div>
                </template>
              </el-table-column>

            </el-table>
          </div>
          <div v-if="rid == 0">
            <el-button type="button" class="pubBtn" @click="edit" v-if="!handleShow">修改</el-button>
            <el-button type="button" class="pubBtn" v-if="handleShow" @click="cancle">取消</el-button>
            <el-button type="button" class="pubBtn3" @click='Update' v-if="handleShow">确定</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="关键词设置" name="three">
          <el-tag :key="tag.name" v-for="tag in dynamicTags" v-if="tag" closable :disable-transitions="false"
            @close="handleClose(tag.id)">
            <span @click="showInput(tag.id)">{{ tag.name }}</span>
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="editVal" ref="saveTagInput" size="small"
            @keyup.enter.native="handleInput" @blur="handleInputConfirm">
          </el-input>
          <div v-if="rid == 0" style="margin:50px 0;display: flex;">
            <el-input v-model="inputValue" style="width:230px;margin-right: 20px;" placeholder="请输入业务关键词"></el-input>
            <el-button slot="append" @click="keyAdd" type="primary">继续添加</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="镇街管理" name="fourth">
          <el-table :data="townData" border style="width: 100%">
            <el-table-column prop="pid" label="级别" align="center">
              <template slot-scope="scope">
                <div>{{ scope.row.pid == 1 ? '一级' : '二级' }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="company" align="center" label="账号名称">
            </el-table-column>
            <el-table-column prop="street_name" align="center" label="镇街">
            </el-table-column>
            <el-table-column prop="login" align="center" label="登录名">
            </el-table-column>
            <el-table-column prop="username" align="center" label="联系人">
            </el-table-column>3
            <el-table-column prop="mobile" align="center" label="联系方式">
            </el-table-column>
            <el-table-column prop="mobile" align="center" label="操作">
              <template slot-scope="scope">
                <el-button type="text" class="editText" @click="exitTown(scope.row)">修改</el-button>
                <el-button type="text" class="ck" @click="resetTown(scope.row.id)">重置密码</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="需求标签" name="label">
          <el-button type="primary" style="margin-left: 10px;" plain @click="addLabel(false)">新增</el-button>
          <div class="label_list">
            <div style="padding: 10px 0 0 10px;">已有标签</div>
            <el-tag v-for="item in demandlabelList" :key="item.name" @click="editLabel(item, false)" closable
              @close="labeClose(item)">{{ item.name }}
            </el-tag>
          </div>
        </el-tab-pane>
        <el-tab-pane label="企业标签" name="company_label">
          <el-button type="primary" style="margin-left: 10px;" plain @click="addLabel(true)">新增</el-button>
          <div class="label_list">
            <div style="padding: 10px 0 0 10px;">已有标签</div>
            <el-tag v-for="item in labelList" :key="item.name" @click="editLabel(item, true)" closable
              @close="labeClose(item)">{{ item.name }}
            </el-tag>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <el-dialog :destroy-on-close="true" :close-on-click-modal='false' title="创建账号" :visible.sync="CreatCancle"
      width="40%" center>
      <el-form ref="form" :model="form" label-width="100px" label-position="left">
        <el-form-item prop="username" label="账号名称">
          <el-input type="username" placeholder="请输入账号名称,将作为账号登录名" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="role_name" label="账号类型">
          <el-input placeholder="请输入账号类型" v-model="form.role_name"></el-input>
          <!--  <el-select type="role_id"  style="width:100%;" v-model="form.role_id" placeholder="请选择账号类型">
              <el-option
                v-for="item in Role"
                :key="item.id"
                :label="item.role_name"
                :value="item.id">
              </el-option>
            </el-select> -->
        </el-form-item>
        <el-form-item prop="position" label="联系人名称">
          <el-input type="position" placeholder="请输入联系人名称" v-model="form.position"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="联系人电话">
          <el-input type="mobile" placeholder="请输入联系人电话" v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="button" class="pubBtn2" @click="CreatCancles">取消操作</el-button>
        <el-button type="button" class="pubBtn" @click="CreatSave('form')">确定创建</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改信息" :visible.sync="dialogupdate">
      <el-form :model="updateForm">
        <el-form-item label="联系人名称" label-width="120px">
          <el-input v-model="updateForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="镇街" label-width="120px">
          <el-input v-model="updateForm.street_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" label-width="120px">
          <el-input v-model="updateForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogupdate = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="dialogResetwrod" @close="passwordClose">
      <el-form :model="ResetwrodForm">
        <el-form-item label="旧密码" label-width="120px">
          <el-input v-model="ResetwrodForm.password_old" autocomplete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" label-width="120px">
          <el-input v-model="ResetwrodForm.password_new" autocomplete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" label-width="120px">
          <el-input v-model="ResetwrodForm.password_new_two" autocomplete="off" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordClose">取 消</el-button>
        <el-button type="primary" @click="passWord">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="addLabelType ? '新增标签' : '修改标签'" :visible.sync="dialogAddlabel" @close="cancel">
      <el-form :model="addlabel">
        <el-form-item label="标签名称" label-width="120px">
          <el-input v-model="addlabel.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirmLabel">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  SettingAuthList, SettingSave, SettingKeywordsList, SettingKeywordsDelete,
  SettingKeywordsAdd, keywordsUpdate, backUserIndex, backUserCreate,
  backUserUpdate, backUserDelete, backUserReset, getRole, backUserInfo
} from "@/api/admin"
import { streetOld, updateUser, passWord, companyLabelIndex, companyLabelAdd, companyLabelDel, companyLabelEdit, demandLabelIndex, demandLabelAdd, demandLabelEdit, demandLabelDel } from '@/api/newuser'
export default {
  data() {
    return {
      companyType: false,
      addLabelType: true,
      readonly: true,
      activeName: 'first',
      tableData: [],
      userData: [],
      Role: [],
      dynamicTags: [],
      inputValue: '',
      handleShow: false,
      system: {
        rivals_num: null,
        notice_user_num: null,
        cost_warning_num: null,
        max_patent_num: null,
        sales_key_num: null
      },
      ResetwrodForm: {
        id: '',
        password_old: '',
        password_new: '',
        password_new_two: '',
      },
      dialogAddlabel: false,
      addlabel: {
        label_id: '',
        name: '',
      },
      inputVisible: false,
      editVal: '',
      edId: null,
      CreatCancle: false,
      form: {
        username: "",
        role_name: "",
        position: "",
        mobile: "",
      },
      exitUserId: "",
      townData: [],
      dialogupdate: false,
      updateForm: {
        id: '',
        username: '',
        mobile: '',
        street_name: '',
      },
      dialogResetwrod: false,
      labelList: [],
      demandlabelList: []
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'name',
      'roles',
      'type',
      'is_admin_view',
      'rid'
    ]),
  },
  async mounted() {
    this.companyLabelIndex();
    this.demandLabelIndex();
    this.streetOld()
    this.getIndex();
    this.getList();
    this.getUserData();
    this.getRole();
  },
  methods: {
    UserListGO(row) {
      // console.log(row);
      this.$router.push({
        path: '/user',
        query: {
          rid: row.rid
        }
      })
    },
    cancel() {
      this.addlabel.name = '';
      this.addlabel.label_id = '';
      this.dialogAddlabel = false;
    },
    editLabel(item, type) {
      this.companyType = type;
      this.addLabelType = false;
      this.addlabel.name = item.name;
      this.addlabel.label_id = item.id;
      this.dialogAddlabel = true;
      // console.log(item);
    },
    labeClose(item) {
      if (this.companyType) {
        this.$confirm('确定删除标签吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async (res) => {
          companyLabelDel({ label_id: item.id }).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.companyLabelIndex();
          }).catch(err => {
            this.$message.error(err.message);
          })
        }).catch(() => {
          this.addlabel.name = '';
          this.addlabel.label_id = '';
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.$confirm('确定删除标签吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async (res) => {
          demandLabelDel({ label_id: item.id }).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.demandLabelIndex();
          }).catch(err => {
            this.$message.error(err.message);
          })
        }).catch(() => {
          this.addlabel.name = '';
          this.addlabel.label_id = '';
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    confirmLabel() {
      if (this.companyType) {
        if (this.addLabelType) {
          companyLabelAdd(this.addlabel).then(res => {
            this.dialogAddlabel = false;
            this.companyLabelIndex();
            this.$message({
              message: '添加成功',
              type: 'success'
            });
          })
        } else {
          companyLabelEdit(this.addlabel).then(res => {
            this.dialogAddlabel = false;
            this.companyLabelIndex();
            this.$message({
              message: '修改成功',
              type: 'success'
            });
          })
        }
      } else {
        if (this.addLabelType) {
          demandLabelAdd(this.addlabel).then(res => {
            this.dialogAddlabel = false;
            this.demandLabelIndex();
            this.$message({
              message: '添加成功',
              type: 'success'
            });
          })
        } else {
          demandLabelEdit(this.addlabel).then(res => {
            this.dialogAddlabel = false;
            this.demandLabelIndex();
            this.$message({
              message: '修改成功',
              type: 'success'
            });
          })
        }
      }


    },
    addLabel(type) {
      this.companyType = type;
      this.addLabelType = true;
      this.dialogAddlabel = true;
    },
    companyLabelIndex() {
      companyLabelIndex().then(res => {
        this.labelList = res
        // console.log(res);
      })
    },
    demandLabelIndex() {
      demandLabelIndex().then(res => {
        this.demandlabelList = res
        // console.log(res);
      })
    },
    passWord() {
      this.$confirm('确定重置密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async (res) => {
        passWord(this.ResetwrodForm).then(res => {
          this.$message({
            type: 'success',
            message: '重置密码成功!'
          })
          this.dialogResetwrod = false
        }).catch(err => {
          this.$message.error(err.message)
        })
      })
    },
    passwordClose() {
      this.ResetwrodForm = {
        id: '',
        password_old: '',
        password_new: '',
        password_new_two: '',
      }
      this.dialogResetwrod = false
    },
    updateUser() {
      updateUser(this.updateForm).then(res => {
        this.dialogupdate = false;
        this.streetOld();
        this.$message({
          message: '修改成功',
          type: 'success'
        });
      })
    },
    streetOld() {
      streetOld().then(res => {
        this.townData = res
      })
    },
    async getRole() {
      try {
        this.Role = await getRole()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    async exitUser(id) {
      try {
        this.exitUserId = id;
        this.CreatCancle = true;
        this.form = await backUserInfo({ id: id })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    deleteUser(id) {
      this.$confirm('确定删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await backUserDelete({ id: id });
          this.getUserData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        } catch (e) {
          this.$message.error(e.message)
        }
      })
    },
    resetUser(id) {
      this.$confirm('确定重置密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await backUserReset({ id: id });
          this.getUserData();
          this.$message({
            type: 'success',
            message: '重置成功!'
          });
        } catch (e) {
          this.$message.error(e.message)
        }
      })
    },
    handleInput() {
      this.inputVisible = true;
    },
    async getUserData() {
      try {
        const res = await backUserIndex();
        this.userData = res
      } catch (e) {
        this.$message.error(e.message)
      }
    },

    async handleInputConfirm() {
      try {
        if (this.editVal) {
          await keywordsUpdate({
            id: this.edId,
            name: this.editVal
          })
          this.getList();
          this.$message.success("修改成功")
        }
        this.inputVisible = false;
        this.editVal = '';
        this.edId = '';
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    showInput(id) {
      this.edId = id;
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus();
      });
    },
    async getIndex() {
      try {
        const res = await SettingAuthList()
        this.tableData = res.list;
        this.system = res.list;
      } catch (e) {
        this.$message.error(e.message)
      }

    },

    async getList() {
      try {
        const list = await SettingKeywordsList()
        this.dynamicTags = list.list
      } catch (e) {
        this.$message.error(e.message)
      }

    },
    async handleClose(id) {
      try {
        await SettingKeywordsDelete({ id: id });
        this.getList()
      } catch (e) {
        this.$message.error(e.message)
      }
      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    edit() {
      this.readonly = false;
      this.handleShow = true;
      this.$nextTick(_ => {
        this.$refs.myNameId.focus();
      });
    },
    async Update() {
      const {
        rivals_num,
        notice_user_num,
        cost_warning_num,
        max_patent_num,
        sales_key_num
      } = this.system[0];
      try {
        await SettingSave({
          rivals_num,
          notice_user_num,
          cost_warning_num,
          max_patent_num,
          sales_key_num
        })
        this.readonly = true;
        this.getIndex();
        this.$message.success("修改成功")
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    async keyAdd() {
      try {
        if (this.inputValue) {
          await SettingKeywordsAdd({ name: this.inputValue })
          this.getList()
          this.$message.success("添加成功")
        }
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    cancle() {
      this.readonly = true;
      this.handleShow = false;
      this.$nextTick(_ => {
        this.$refs.myNameId.blur();
      });
      this.getIndex()
    },
    CreatCancles() {
      this.exitUserId = '';
      this.CreatCancle = false;
    },
    async CreatSave(formName) {
      if (this.exitUserId) {
        try {
          const {
            username,
            role_name,
            position,
            mobile,
          } = this.form;
          await backUserUpdate({
            username,
            role_name,
            position,
            mobile,
            id: this.exitUserId
          })
          this.exitUserId = '';
          this.$refs[formName].resetFields();
          this.CreatCancle = false;
          this.getUserData();
        } catch (e) {
          this.$message.error(e.message)
        }
      } else {
        try {
          const {
            username,
            role_name,
            position,
            mobile,
          } = this.form;
          await backUserCreate({
            username,
            role_name,
            position,
            mobile,
          })
          this.exitUserId = '';
          this.CreatCancle = false;
          this.$refs[formName].resetFields();
          this.getUserData();
          this.$alert('创建成功,默认密码123456。请尽快登录修改密码', {
            confirmButtonText: '确定',
            callback: action => {
              // this.$message({
              //   type: 'info',
              //   message: `action: ${ action }`
              // });
            }
          });
          // this.$message.success("")
        } catch (e) {
          this.$message.error(e.message)
        }
      }
    },

    exitTown(item) {
      try {
        this.updateForm.id = item.id
        this.updateForm.username = item.username
        this.updateForm.mobile = item.mobile
        this.updateForm.street_name = item.street_name
        this.dialogupdate = true;
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    resetTown(id) {
      this.ResetwrodForm.id = id
      this.dialogResetwrod = true;
    }
  }
}
</script>

<style scoped lang="less">
.pagination {
  margin: 15px 0;
}

.el-pagination {
  text-align: right;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.label_title {
  font-size: 24px;
  font-weight: bold;
}

.label_list {
  width: 80%;

  .el-tag {
    margin-left: 10px;
    margin-top: 5px;
  }
}
</style>
